﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Xml;

namespace Hands.FileCache
{
    internal abstract class Cache
    {
        private const string CONFIG_FILE_NAME = "cache.xml";
        private readonly string basePath = null;

        protected Cache()
        {
            if (basePath == null)
            {
                basePath = HttpRuntime.AppDomainAppPath.ToString();
                readConfig();
            }
        }

        private const string DEFAULT_PATH = "default-path";
        private const string TAG_NAME = "file";
        private const string FILE_TYPE = "filetype";
        private const string FILE_NAME = "filename";

        private void readConfig()
        {
            string xmlPath = basePath + CONFIG_FILE_NAME;
            XmlDocument configFile = new XmlDocument();
            configFile.Load(xmlPath);

            XmlNodeList defaultNodes = configFile.GetElementsByTagName(DEFAULT_PATH);
            string defaultPath = defaultNodes[0].InnerText;

            XmlNodeList nodes = configFile.GetElementsByTagName(TAG_NAME);
            foreach (XmlNode node in nodes)
            {
                File file = new File(node.Attributes[FILE_NAME].Value, node.Attributes[FILE_TYPE].Value, basePath + node.InnerText);
                addFileToCache(file);
            }
        }

        protected abstract void addFileToCache(File file);
    }
}
